<template>
  <div>
    <div class="page-title">个人中心</div>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="profile-card" v-loading="loadingUserInfo">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="primary" text @click="refreshUserInfo" :loading="loadingUserInfo">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="profile-info">
            <div class="info-item">
              <label>用户名：</label>
              <span>{{ userInfo?.username }}</span>
            </div>
            <div class="info-item">
              <label>昵称：</label>
              <span>{{ userInfo?.nickname }}</span>
            </div>
            <div class="info-item">
              <label>邮箱：</label>
              <span>{{ userInfo?.email || '-' }}</span>
            </div>
            <div class="info-item">
              <label>手机号：</label>
              <span>{{ userInfo?.phone || '-' }}</span>
            </div>
            <div class="info-item">
              <label>角色：</label>
              <el-tag>{{ userInfo?.role === 'admin' ? '管理员' : '美容师' }}</el-tag>
            </div>
            <div class="info-item">
              <label>注册时间：</label>
              <span>{{ formatDate(userInfo?.createdAt) }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import request from '@/api/request'

const authStore = useAuthStore()

const userInfo = computed(() => authStore.userInfo)
const loadingUserInfo = ref(false)

const passwordFormRef = ref<FormInstance>()
const loading = ref(false)

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules: FormRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 查询用户数据
const queryUserInfo = async () => {
  loadingUserInfo.value = true
  try {
    const response = await request({
      url: '/user/query',
      method: 'post',
      data: {
        id: userInfo.value?.id
      }
    })
    
    if (response.data) {
      // 更新store中的用户信息
      authStore.setUserInfo(response.data)
      ElMessage.success('用户信息已更新')
    }
  } catch (error) {
    console.error('查询用户信息失败:', error)
    ElMessage.error('查询用户信息失败')
  } finally {
    loadingUserInfo.value = false
  }
}

// 刷新用户信息
const refreshUserInfo = () => {
  queryUserInfo()
}

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 这里调用修改密码的API
        ElMessage.success('密码修改成功')
        passwordForm.value = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
      } catch (error) {
        console.error('修改密码失败:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

const formatDate = (date?: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 页面加载时查询用户数据
onMounted(() => {
  queryUserInfo()
})
</script>

<style scoped>
.profile-card {
  height: fit-content;
}

.profile-info {
  text-align: center;
}

.avatar-container {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 15px;
  text-align: left;
}

.info-item label {
  font-weight: bold;
  color: #666;
  margin-right: 8px;
}

.info-item span {
  color: #333;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>